package com.hedl.practice.diyJava.network_programming.UDP_programming.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Server {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(6666);   //监听指定端口
        System.out.println("server is running...");

        for (;;){
            //接受
            byte[] buffer = new byte[1024];

            //构造 DatagramPacket用于接收长度为 length数据包。
            DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
            ds.receive(packet);     //从此套接字接收数据报包
            /**
             * packet.getData()==返回数据缓冲区。
             * packet.getOffset()==要发送的数据的偏移量或接收数据的偏移量
             */
            String cmd = new String(packet.getData(),packet.getOffset(),packet.getLength(), StandardCharsets.UTF_8);

            //发送
            String resp = "bad command";
            switch (cmd){
                case "date":
                    resp = LocalDate.now().toString();
                    break;
                case "time":
                    resp = LocalTime.now().withNano(0).toString();
                    break;
                case "datetime":
                    resp = LocalDateTime.now().withNano(0).toString();
                    break;
                case "weather":
                    resp = "sunny,10~15 c.";
                    break;
            }
            System.out.println(cmd + ">>> "+resp);
            //设置此数据包的数据缓冲区。
            packet.setData(resp.getBytes(StandardCharsets.UTF_8));
            ds.send(packet);        //从此套接字发送数据报包
        }
    }
}
